using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Domain.Interfaces;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Domain.Services;
using UniversalAdmin.Infrastructure.Data;
using UniversalAdmin.Infrastructure.Data.Seed;
using UniversalAdmin.Infrastructure.Repositories;
using UniversalAdmin.Infrastructure.Services;

namespace UniversalAdmin.Infrastructure;

public static class DependencyInjection
{
  public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
  {
    // 从配置文件中读取连接字符串
    string? connectionString = configuration.GetConnectionString("RemotePostgreSql");

    if (string.IsNullOrEmpty(connectionString))
    {
      throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
    }

    // 配置 DbContext
    services.AddDbContext<UniversalAdminDbContext>(options =>
        options.UseNpgsql(connectionString));


    // 注册应用服务
    services.AddScoped<IPasswordHasher, PasswordHasher>();
    services.AddScoped<IJwtService, JwtService>();
    services.AddScoped<IAuthService, AuthService>();
    services.AddScoped<IUserService, UserService>();
    services.AddScoped<IFileService, FileService>();
    services.AddScoped<IArticleService, ArticleService>();
    services.AddScoped<IArticleCategoryService, ArticleCategoryService>();

    // ✅ 显式注册仓储接口
    services.AddScoped<IMenuRepository, MenuRepository>();
    services.AddScoped<IUserRepository, UserRepository>();
    services.AddScoped<IRoleRepository, RoleRepository>();
    services.AddScoped<ISystemConfigRepository, SystemConfigRepository>();
    services.AddScoped<IOperationLogRepository, OperationLogRepository>();
    services.AddScoped<IFileRepository, FileRepository>();
    services.AddScoped<IArticleRepository, ArticleRepository>();
    services.AddScoped<IArticleCategoryRepository, ArticleCategoryRepository>();
    services.AddScoped<RoleManager>();

    // 添加其他依赖项（如果有）
    // 注册 UnitOfWork
    services.AddScoped<IUnitOfWork, UnitOfWork>();

    return services;
  }
  // 添加新的扩展方法用于初始化数据库
  public static async Task InitializeDatabaseAsync(this IServiceProvider serviceProvider)
  {
    using var scope = serviceProvider.CreateScope();
    var services = scope.ServiceProvider;

    try
    {
      var context = services.GetRequiredService<UniversalAdminDbContext>();

      // 应用迁移
      await context.Database.MigrateAsync();

      // 初始化种子数据
      await DataSeeder.SeedAsync(context);
    }
    catch (Exception ex)
    {
      var logger = services.GetRequiredService<ILogger<UniversalAdminDbContext>>();
      logger.LogError(ex, "初始化数据库时发生错误");
      throw;
    }
  }
}